package top.rainf.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import top.rainf.constants.AttributeConstants;
import top.rainf.domain.dto.ReplyFullInfo;
import top.rainf.domain.dto.UserFullInfo;
import top.rainf.domain.vo.Post;
import top.rainf.domain.vo.UserBaseInfo;
import top.rainf.domain.vo.UserPersonalInfo;
import top.rainf.service.*;
import top.rainf.service.impl.UserBaseInfoService;
import top.rainf.support.Result;
import top.rainf.domain.vo.PostReply;
import top.rainf.support.StringMatcher;
import top.rainf.support.TokenGenerator;
import top.rainf.support.VerifyUtil;
import top.rainf.util.PagerUtil;
import top.rainf.util.StringUtil;

import java.util.*;

/**
 * @author 星环
 * @date Wed May 10 21:04:41 CST 2023
 * @description 回帖的控制器类 由本人的生成器自动生成~
 */
@RestController
@Slf4j
@RequestMapping("/postReply")
public class PostReplyController {
    @Autowired
    IPostReplyService postReplyService;

    @Autowired
    INoticeService noticeService;

    @Autowired
    IPostService postService;
    @Autowired
    IUserBaseInfoService userBaseInfoService;
    @Autowired
    IUserPersonalInfoService userPersonalInfoService;

    /**
    * 获取全部回帖的列表
    * @return 返回是否获取成功~
    */
    @RequestMapping("/list")
    public Result list(){
        List<PostReply> list = postReplyService.getPostReplyList();
        if(list == null){
            return Result.fail();
        }
        return Result.success().addObj("list",list);
    }

    /**
    * 根据id获取一个回帖
    * @return 返回是否获取成功~
    */
    @RequestMapping("/one")
    public Result getOnePostReply(int id){
        PostReply postReply = postReplyService.getOneById(id);
        if(postReply == null){
                    return Result.fail();
        }
        return Result.success().addObj("data",postReply);
    }
    /**
    * 根据id删除一个回帖
    ---------------------------
    * @param id 要删除的回帖的id
    * @return 返回是否获取成功~
    */
    @RequestMapping("/deleteById")
    public Result deleteById(int id,int userId,@SessionAttribute(AttributeConstants.LOGIN_TOKEN) String token){
        String ver = VerifyUtil.checkToken(token, userId);
        if (!StringUtil.isNullOrEmpty(ver)){
            return Result.fail("请登录后操作！");
        }
        boolean suc = postReplyService.deleteOneById(id);
        return suc ? Result.success() : Result.fail();
    }

    @RequestMapping("/deleteByIds")
    public Result deleteByIds(List<Integer> idList){
        boolean suc = postReplyService.deleteAll(idList);
        return suc ? Result.success() : Result.fail();
    }

    @RequestMapping("update")
    public Result update(PostReply postReply){
        boolean suc = postReplyService.updateById(postReply);
        return suc ? Result.success() : Result.fail();
    }


    @RequestMapping("/replyOne")
    public Result replyOne(PostReply postReply, @SessionAttribute(AttributeConstants.LOGIN_TOKEN)String token){
        //验证用户有没有登录
        if(token == null){
            return Result.fail("您还未登录");
        }
        int uid = TokenGenerator.getUserIdFromToken(token);
        if(uid != postReply.getUserId()){
            return Result.fail("信息有误，请重新登录！");
        }
    //    向贴主发信息
        int ret = postReplyService.addOne(postReply);

        sendAtNotice(postReply.getContent(),postReply.getContent().substring(0,Math.min(20,postReply.getContent().length())));

        return ret == 1 ? Result.success("回复成功！") : Result.fail("回复失败！");
    }

    private void sendAtNotice(String content,String title) {
        String[] strings = StringMatcher.extractMatches(content, "@\\w+");
        List<String> atUsers = new ArrayList<>(5);

        for (String string : strings) {
            atUsers.add(string.substring(1));
        }

        log.info("这些是@的人{}",atUsers.toString());
        List<Integer> idByUsernames = userBaseInfoService.getIdByUsernames(atUsers);
        for (Integer id : idByUsernames) {
            noticeService.sendTo(id,"您在帖子‘" + title + "’中被@了");
        }
    }

    @RequestMapping("/getPostPage")
    public Result getPostPage(int postId,int curPage,int numPerPage){
        List<PostReply> replyListPre = postReplyService.getReplyListByPostIdPaged(postId, curPage, numPerPage);
    //    获取所有uid
        Set<Integer> uidSet = new HashSet<>();
        replyListPre.forEach(r->uidSet.add(r.getUserId()));
        List<Integer> uidList = uidSet.stream().toList();
    //    获取所有用户信息
        List<UserBaseInfo> baseList = userBaseInfoService.getByIds(uidList);
        List<UserPersonalInfo> moreList = userPersonalInfoService.getByIds(uidList);
    //    组装
        Map<Integer, UserFullInfo> userMap = new HashMap<>();
        uidList.forEach(uid->userMap.put(uid,new UserFullInfo()));
        baseList.forEach(base->userMap.get(base.getId()).setBase(base));
        moreList.forEach(more->userMap.get(more.getUserId()).setMore(more));
    //    组装ReplyList
        List<ReplyFullInfo> replyList = new ArrayList<>();
        replyListPre.forEach(r->{
            ReplyFullInfo rfi = new ReplyFullInfo();
            rfi.setUser(userMap.get(r.getUserId()));
            rfi.setReply(r);
            replyList.add(rfi);
        });
        //pagerList
        int totalCount = postReplyService.getReplyCountInPost(postId);
        List<String > pageList = PagerUtil.getPageListStr(numPerPage,curPage,totalCount);
        return Result.success().addObj("replyList",replyList)
                .addObj("pageList",pageList);
    }
}
